package com.hilda.twitter.samples.timeline.ui.activities;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

import com.hilda.twitter.samples.timeline.R;
import com.hilda.twitter.samples.timeline.twitter.TwitterApp;
import com.hilda.twitter.samples.timeline.twitter.TwitterApp.TwitterDialogListener;

public class LoginActivity extends Activity {
	private TwitterApp mTwitter;
	private Button mButton;

	private final TwitterDialogListener mTwLoginDialogListener = new TwitterDialogListener() {
		@Override
		public void onComplete(String value) {
			String username = mTwitter.getUsername();
			username = (username.equals("")) ? "No Name" : username;

			Toast.makeText(LoginActivity.this,
					"Connected to Twitter as " + username, Toast.LENGTH_LONG)
					.show();

			startActivity(new Intent(LoginActivity.this, MainActivity.class));
			finish();
		}

		@Override
		public void onError(String value) {
			Toast.makeText(LoginActivity.this, "Twitter connection failed",
					Toast.LENGTH_LONG).show();
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);

		mButton = (Button) findViewById(R.id.button);

		mButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mTwitter.authorize();
			}
		});

		mTwitter = new TwitterApp(this);

		mTwitter.setListener(mTwLoginDialogListener);

		if (mTwitter.hasAccessToken()) {
			startActivity(new Intent(this, MainActivity.class));
			finish();
		}
	}
}